package com.example.uavstatus;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;


public class UAVStatusService extends Service {
    private static final String TAG = "UAVStatusService";
    private static final int NOTIFICATION_ID = 101;
    private static final String CHANNEL_ID = "status_channel";
    private DJIConnection djiConnection;
    private SharedPreferences preferences;

    @Override
    public void onCreate() {
        super.onCreate();
        preferences = getSharedPreferences("uav_settings", Context.MODE_PRIVATE);
        djiConnection = new DJIConnection(this, preferences);
        createNotificationChannel();
        startForeground(NOTIFICATION_ID, createNotification());
        Log.d(TAG, "服务已创建");
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "无人机控制服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("无人机状态监控与远程控制服务");
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }

    private Notification createNotification() {
        // 从设置中获取配置信息
        String serverIp = preferences.getString("server_ip", "192.168.1.11");
        int controlPort = preferences.getInt("control_port", 4321);
        int dataPort = preferences.getInt("data_port", 1234);

        String notificationText = String.format(
                "控制端口:%d | 数据端口:%d | 目标IP:%s",
                controlPort,
                dataPort,
                serverIp
        );

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_drone)
                .setContentTitle("无人机控制服务")
                .setContentText(notificationText)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "服务启动命令");
        if (djiConnection != null) {
            djiConnection.initSDK();
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "服务销毁");
        if (djiConnection != null) {
            djiConnection.release();
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}